package com.skytech.chatim.sky.xmlapi;



import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.skytech.chatim.sky.xmlapi.command.XmlApiCommand;

/**
 * Created by Vega on 2015/1/7.
 */
public class XmlApiRequest {
    private static final String PREFIX = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        + "<serv:message  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:serv=\"http://www.webex.com/schemas/2002/06/service\">";

    private static final String SUFFIX = "</serv:message>";

    private String user;
    private String password;
    private String siteName;
    private List<XmlApiCommand> commands = new ArrayList<XmlApiCommand>();

    public XmlApiRequest(String user, String password, String siteName, XmlApiCommand command) {
        this.user = user;
        this.password = password;
        this.siteName = siteName;
        this.commands.add(command);
    }

    private String generateHeader() {
        Document doc = DocumentHelper.createDocument();
        Element header = doc.addElement("header");
        Element securityContext = header.addElement("securityContext");
        securityContext.addElement("siteName").setText(siteName);
        if (user != null) {
            securityContext.addElement("webExID").setText(user);
        }
        if (password != null) {
            securityContext.addElement("password").setText(password);
        }
        return WbxClientUtils.doc2string(doc, true);
    }

    private String generateBody() {
        StringBuilder builder = new StringBuilder();
        builder.append("<body>");
        for (XmlApiCommand command : commands) {
            if (command != null) {
                builder.append(command.toXML());
            }
        }
        return builder.append("</body>").toString();
    }

    public String toXML() {
        return PREFIX + generateHeader() + generateBody() + SUFFIX;
    }
}
